<template>
	<view class="userInfo">
		<view class="TopNav">
			<view class="back"></view>
			<view :class="['all-check', isSubmit ? 'active' : '']" @click="submit">完成</view>
		</view>

		<view class="avatar_box">
			<view class="avatar" @click="previewImage">
				<image style="width: 100%;" :src="avatar" mode="widthFix"></image>
			</view>
			<view class="avatar_btn" @click="editAvatar">编辑</view>
			<view class="tips">选择头像后，请点击完成按钮更新头像</view>
		</view>

		<view class="form">
			<uni-forms ref="form" :modelValue="formData" :rules="rules" label-position="top">
				<uni-forms-item label="昵称" name="name">
					<!-- <input class="input" type="text" v-model="formData.name" name="name" placeholder="添加标题" /> -->
					<uni-easyinput
						class="input"
						type="text"
						autoHeight
						v-model="formData.name"
						:clearable="false"
						:inputBorder="false"
						placeholder="请输入昵称"
					/>
				</uni-forms-item>
				<uni-forms-item label="登录邮箱" name="email">
					<!-- <uni-easyinput
						class="input"
						type="text"
						autoHeight
						v-model="formData.email"
						:clearable="false"
						:inputBorder="false"
						disabled
						placeholder="请输入邮箱"
					/> -->
					<text class="input disabled">{{ formData.email }}</text>
				</uni-forms-item>
				<uni-forms-item label="个人简介" name="profile">
					<!-- <uni-easyinput
						class="input"
						type="textarea"
						autoHeight
						v-model="formData.profile"
						:clearable="false"
						:inputBorder="true"
						placeholder="请输入个人简介"
					/> -->
					<textarea class="textarea" :value="formData.profile" placeholder="请输入个人简介" />
				</uni-forms-item>
			</uni-forms>
		</view>
	</view>
</template>

<script>
import api from '@/common/api.js';
import TopNav from '@/components/TopNav/TopNav.vue';
export default {
	components: {
		TopNav
	},
	data() {
		return {
			formData: {
				name: '',
				email: '',
				profile: ''
			},
			rules: {
				name: {
					rules: [
						{
							required: true,
							errorMessage: '请输入昵称'
						}
					]
				}
			},
			avatar: '',
			avatarUrl: '', // 头像不带服务器地址
			initNickName: '', // 初始昵称
			initProfile: '', // 初始个人简介
			isSubmit: false, // 是否可提交
			changeAvatar: false, // 头像被改变
		};
	},
	watch: {
		formData: {
			handler(newVal, oldVal) {
				console.log('表单发生变化');
				console.log(this.initNickName);
				console.log('new ==>', newVal);
				console.log('old ==>', oldVal);
				if (this.initNickName != newVal.name || this.initProfile != newVal.profile || this.changeAvatar) {
					this.isSubmit = true;
				} else {
					this.isSubmit = false;
				}
			},
			deep: true
		}
	},
	computed: {
		isLogin() {
			return this.$store.state.isLogin;
		},
		userInfo() {
			return this.$store.state.userinfo;
		}
	},
	onLoad() {
		console.log('userInfo ==>', this.userInfo);
		if (this.userInfo) {
			if (this.userInfo.avatar) {
				this.avatarUrl = this.userInfo.avatar;
				if (this.userInfo.avatar.includes('https')) {
					this.avatar = this.userInfo.avatar;
				} else {
					this.avatar = this.$baseURL + this.userInfo.avatar;
				}
			}
			this.formData.name = this.userInfo.nick_name;
			this.formData.email = this.userInfo.email;
			this.formData.profile = this.userInfo.user_info.profile;
			this.initNickName = this.userInfo.nick_name;
			this.initProfile = this.userInfo.user_info.profile;
		}
	},
	methods: {
		previewImage() {
			uni.previewImage({
				urls: [this.avatar]
			});
		},

		// 编辑头像
		editAvatar() {
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: res => {
					uni.showLoading({
						title: '上传中'
					});
					console.log(JSON.stringify(res.tempFilePaths));
					let tempFilePaths = res.tempFilePaths;
					uni.uploadFile({
						url: api.upload,
						filePath: tempFilePaths[0],
						name: 'file',
						success: uploadFileRes => {
							console.log(uploadFileRes);
							let data = JSON.parse(uploadFileRes.data);
							console.log(data);
							if (data.code != '200') {
								uni.hideLoading();
								uni.showToast({
									title: '上传失败',
									icon: 'error'
								});
								return false;
							}
							this.avatarUrl = data.data.avatar;
							this.avatar = this.$baseURL + data.data.avatar;
							this.changeAvatar = true;
							this.isSubmit = true;
							uni.hideLoading();
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							})
						},
						fail: e => {
							uni.hideLoading();
							console.log(e);
						}
					});
				}
			});
		},
		
		// 提交
		async submit() {
			if (!this.isSubmit) {
				return false;
			}
			let isPass = await this.validateForm();
			if (!isPass) {
				return false;
			}
			
			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.showToast({
					title: '请登录',
					duration: 1000,
					icon: 'error',
					complete() {
						setTimeout(() => {
							uni.navigateTo({
								url: '../loginWays/loginWays'
							});
						}, 1000);
					}
				});
			}
			
			let params = {
				avatar: this.avatarUrl,
				nick_name: this.formData.name,
				profile: this.formData.profile
			}
			
			try {
				let res = await this.$ajax.put({
					url: api.updataUserInfo,
					data: params,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('编辑成功 ==>', res);
				if (res.statusCode == 200) {
					this.$store.commit('saveUserInfo', params);
					uni.showToast({
						title: '您的个人资料已更新',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 1000);
				}
			} catch (e) {
				console.log(e);
			}
		},
		
		// 表单验证的方法
		validateForm() {
			return new Promise((resolve, reject) => {
				this.$refs.form
					.validate()
					.then(res => {
						resolve(true);
					})
					.catch(err => {
						resolve(false);
					});
			});
		},
	}
};
</script>

<style lang="scss">
.userInfo {
	padding: 20rpx 32rpx 0;

	.TopNav {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #fff;
		margin-bottom: 20rpx;
		.all-check {
			height: 90;
			border-radius: 44rpx;
			background-color: #efefef;
			color: #999;
			font-size: 32rpx;
			letter-spacing: 2rpx;
			text-align: center;
			line-height: 90rpx;
			padding: 0 24rpx;
			&.active {
				background-color: #e60023;
				color: #fff;
			}
		}
	}

	.avatar_box {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin-bottom: 40rpx;
	}
	.avatar {
		position: relative;
		width: 250rpx;
		height: 250rpx;
		border-radius: 50%;
		overflow: hidden;
		background-color: #efefef;
		margin-bottom: 20rpx;
		z-index: 10;
	}
	.avatar_btn {
		width: 100rpx;
		height: 80rpx;
		border-radius: 44rpx;
		background-color: #efefef;
		font-size: 28rpx;
		letter-spacing: 2rpx;
		text-align: center;
		line-height: 80rpx;
		color: #111;
	}

	.form {
		// padding: 32rpx;
		.form-item {
			margin-bottom: 40rpx;
		}
		.title {
			margin-bottom: 20rpx;
		}
		.input {
			font-size: 36rpx;
			// text-shadow: 0px 0px #000;
		}
	}
	/deep/ .uni-forms-item__content {
		// min-height: 0;
		line-height: 72rpx;
	}
	/deep/ .uni-forms-item__label .label-text {
		font-size: 32rpx;
		color: #111;
	}
	.uni-easyinput__content-input {
		font-size: 36rpx !important;
		text-shadow: 0px 0px #000 !important;
		padding: 0 !important;
	}
	// .uni-easyinput__content {
	// 	min-height: 0 !important;
	// }
	/deep/.uni-error-message {
		position: relative;
		bottom: 20px;
	}
	.disabled {
		color: #999 !important;
	}
	.tips {
		font-size: 28rpx;
		color: #999;
		margin-top: 20rpx;
	}
	.textarea {
		font-size: 36rpx;
	}
}
</style>
